//
//  HLTextView.m
//  OrderSys
//
//  Created by 1 on 2017/7/6.
//  Copyright © 2017年 com.hx. All rights reserved.
//

#import "HLTextView.h"

@implementation HLTextView

- (void)dealloc
{
     NSLog(@"%@ 这个类被强暴了",NSStringFromClass([self class]));
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//- (id)initWithFrame:(CGRect)frame
//{
//    if ((self = [super initWithFrame:frame])) {
//         [self _init];
//    }
//    return self;
//}

-(instancetype)init
{
    if ((self = [super init])) {
        
        [self _init];
    }
    return self;
}

-(void)_init
{
    self.placeholder = @"";
    
    self.placeholderX =8;
    
    self.font = kSysFont(kFitW(13));
    
    self.placeholderColor = [UIColor lightGrayColor];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
    
}



- (void)textChanged:(NSNotification *)notification
{
    if (self.placeholder.length == 0)
        return;
    
    if (self.text.length == 0) {
        [[self viewWithTag:999] setAlpha:1];
    } else {
        [[self viewWithTag:999] setAlpha:0];
    }
}





- (void)setText:(NSString *)text
{
    [super setText:text];
    
    [self textChanged:nil];
}



- (void)drawRect:(CGRect)rect
{
    if (self.placeholder.length > 0) {
        if (!_placeholderLabel) {
            _placeholderLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.placeholderX, 8, self.bounds.size.width - 2*self.placeholderX, 0)];
            _placeholderLabel.lineBreakMode = NSLineBreakByWordWrapping;
            _placeholderLabel.numberOfLines = 0;
            _placeholderLabel.font = self.font;
            _placeholderLabel.backgroundColor = [UIColor clearColor];
            _placeholderLabel.textColor = self.placeholderColor;
            _placeholderLabel.alpha = 0;
            _placeholderLabel.tag = 999;
            [self addSubview:_placeholderLabel];
        }
        
        _placeholderLabel.textAlignment = self.textAlignment;
        _placeholderLabel.text = self.placeholder;
        [_placeholderLabel sizeToFit];
        CGRect frame = _placeholderLabel.frame;
        frame.size.width = self.bounds.size.width - 4.5* 2;//self.frame.origin.x * 2;
        _placeholderLabel.frame = frame;
        [self sendSubviewToBack:_placeholderLabel];
    }
    
    if (self.text.length == 0 && self.placeholder.length > 0) {
        [[self viewWithTag:999] setAlpha:1];
    }
    
    [super drawRect:rect];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
